package com.example.user.adapter.in.web.controller;

import com.example.user.adapter.in.web.dto.CreateUserRequestDTO;
import com.example.user.adapter.in.web.dto.UpdateUserRequestDTO;
import com.example.user.adapter.in.web.dto.UserResponseDTO;
import com.example.user.service.application.command.CreateUserCommand;
import com.example.user.service.application.command.UpdateUserCommand;
import com.example.user.service.application.port.in.*;
import com.example.user.service.domain.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
public class UserController {

    private final GetUserListUseCase getUserListUseCase;
    private final CreateUserUseCase createUserUseCase;
    private final DeleteUserUseCase deleteUserUseCase;
    private final UpdateUserUseCase updateUserUseCase;
    private final GetUserByIdUseCase getUserByIdUseCase;

    @GetMapping("")
    public List<User> getUsers() {
        log.info("getUsers");
        return getUserListUseCase.getUsers();
    }

    @PostMapping()
    public User createUser(@RequestBody CreateUserRequestDTO createUserRequestDTO){

        CreateUserCommand command=CreateUserCommand.builder()
                .name(createUserRequestDTO.name())
                .age(createUserRequestDTO.age())
                .email(createUserRequestDTO.email())
                .build();

        return createUserUseCase.createUser(command);
    }


    @DeleteMapping("{id}")
    public String deleteUser(@PathVariable("id") Long id){
        deleteUserUseCase.deleteUser(id);
        return "success";
    }

    /**
     * @author liuxin
     * @param updateUserRequestDTO
     * @return
     */
    @PutMapping("")
    public User updateUser(@RequestBody UpdateUserRequestDTO updateUserRequestDTO){
        UpdateUserCommand command=UpdateUserCommand.builder()
                .id(updateUserRequestDTO.id())
                .name(updateUserRequestDTO.name())
                .age(updateUserRequestDTO.age())
                .email(updateUserRequestDTO.email())
                .build();
        User user = updateUserUseCase.updateUser(command);
        return user;
    }


    /**
     * @author dengli
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public UserResponseDTO getUserById(@PathVariable("id") Long id){
        User user = getUserByIdUseCase.getUserById(id);
        UserResponseDTO userResponseDTO = new UserResponseDTO(
                user.getId().id(),
                user.getName().username(),
                user.getAge().age(),
                user.getEmail().email());
        return userResponseDTO;
    }
}
